package com.cai.servlet.user;

import com.cai.dao.UserDao;
import com.cai.dao.impl.UserDaoImpl;
import com.cai.util.CreatCodeUtil;
import com.cai.util.MailMessageUtil;
import com.cai.util.MailUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author RuoLi
 */
@WebServlet(name = "ServletUserForget", value = "/User/UserForgetPassword")
public class ServletUserForgetPassword extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        MailMessageUtil messageUtil = new MailMessageUtil();
        UserDao userDao = new UserDaoImpl();
        //生成随机字符作为密码
        String code = CreatCodeUtil.createCode();
        //接收参数，发送邮件
        String userAccount = req.getParameter("UserAccount");
        String userMail = req.getParameter("UserMail");
        //检查账号是否存在
        int count=userDao.AccountExist(userAccount);
        System.out.println("count = " + count);
        if (count == 0) {
            resp.getWriter().println(0);
        }else {
            //重置账号密码
            userDao.updateUserPassword(userAccount, userMail, code);
            //发送邮件
            MailUtil.sendMail(messageUtil.sendNewPassword(userMail, code, userAccount));
        }
    }
}
